<template>
  <div class="activity-management">
    <div class="page-header">
      <h2>活动管理</h2>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        创建活动
      </el-button>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="活动状态">
          <el-select v-model="queryParams.status" placeholder="全部状态" clearable>
            <el-option label="未开始" :value="0" />
            <el-option label="报名中" :value="1" />
            <el-option label="进行中" :value="2" />
            <el-option label="已结束" :value="3" />
            <el-option label="已取消" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否推荐">
          <el-select v-model="queryParams.isRecommended" placeholder="全部" clearable>
            <el-option label="是" :value="true" />
            <el-option label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 活动列表 -->
    <el-table
      v-loading="loading"
      :data="activityList"
      border
      stripe
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="活动标题" min-width="180" show-overflow-tooltip />
      <el-table-column prop="location" label="活动地点" min-width="120" show-overflow-tooltip />
      <el-table-column label="活动时间" min-width="180" show-overflow-tooltip>
        <template #default="scope">
          {{ formatDate(scope.row.startTime) }} 至 {{ formatDate(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="报名人数" width="100" align="center">
        <template #default="scope">
          {{ scope.row.registeredNumber }}/{{ scope.row.recruitNumber }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否推荐" width="100" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isRecommended"
            @change="handleRecommendChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            v-if="scope.row.status === 0"
            type="success"
            size="small"
            @click="updateStatus(scope.row.id, 1)"
          >
            开始报名
          </el-button>
          <el-button
            v-if="scope.row.status === 1"
            type="warning"
            size="small"
            @click="updateStatus(scope.row.id, 2)"
          >
            开始活动
          </el-button>
          <el-button
            v-if="scope.row.status === 2"
            type="info"
            size="small"
            @click="updateStatus(scope.row.id, 3)"
          >
            结束活动
          </el-button>
          <el-button
            v-if="scope.row.status < 3"
            type="danger"
            size="small"
            @click="updateStatus(scope.row.id, 4)"
          >
            取消活动
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
            :disabled="scope.row.status === 2"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 创建/编辑活动对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入活动地点" />
        </el-form-item>
        <el-form-item label="活动时间" prop="activityTime">
          <el-date-picker
            v-model="form.activityTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="报名时间" prop="registerTime">
          <el-date-picker
            v-model="form.registerTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="招募人数" prop="recruitNumber">
          <el-input-number v-model="form.recruitNumber" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item label="活动封面" prop="coverImg">
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-change="handleCoverChange"
            :on-remove="handleCoverRemove"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动详情" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="5"
            placeholder="请输入活动详情"
          />
        </el-form-item>
        <el-form-item label="所属团队" prop="team">
          <el-input v-model="form.team" placeholder="请输入所属团队/学院" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Search, Refresh } from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user';
import { 
  getActivityList, 
  createActivity, 
  updateActivity, 
  deleteActivity, 
  recommendActivity, 
  updateActivityStatus 
} from '@/api/activity';

const userStore = useUserStore();

// 查询参数
const queryParams = reactive({
  status: null,
  isRecommended: null,
  page: 1,
  size: 10
});

// 加载状态
const loading = ref(false);
// 活动列表
const activityList = ref([]);
// 总记录数
const total = ref(0);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = computed(() => form.id ? '编辑活动' : '创建活动');
const formRef = ref(null);

// 表单数据
const form = reactive({
  id: null,
  title: '',
  location: '',
  activityTime: [],
  registerTime: [],
  recruitNumber: 10,
  coverImg: '',
  description: '',
  team: '',
  status: 0,
  creatorId: null
});

// 表单校验规则
const rules = {
  title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
  location: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
  activityTime: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
  registerTime: [{ required: true, message: '请选择报名时间', trigger: 'change' }],
  recruitNumber: [{ required: true, message: '请输入招募人数', trigger: 'blur' }],
  description: [{ required: true, message: '请输入活动详情', trigger: 'blur' }]
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '未开始',
    1: '报名中',
    2: '进行中',
    3: '已结束',
    4: '已取消'
  };
  return statusMap[status] || '未知';
};

// 获取状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'primary',
    4: 'danger'
  };
  return typeMap[status] || '';
};

// 查询活动列表
const fetchActivityList = async () => {
  loading.value = true;
  try {
    const params = {
      ...queryParams,
      page: queryParams.page - 1 // 后端从0开始
    };
    const res = await getActivityList(params);
    if (res.code === 200) {
      activityList.value = res.data;
      total.value = res.total || res.data.length;
    }
  } catch (error) {
    console.error('获取活动列表失败:', error);
    ElMessage.error('获取活动列表失败');
  } finally {
    loading.value = false;
  }
};

// 查询按钮点击
const handleQuery = () => {
  queryParams.page = 1;
  fetchActivityList();
};

// 重置查询条件
const resetQuery = () => {
  queryParams.status = null;
  queryParams.isRecommended = null;
  queryParams.page = 1;
  fetchActivityList();
};

// 处理分页大小变更
const handleSizeChange = (size) => {
  queryParams.size = size;
  fetchActivityList();
};

// 处理页码变更
const handleCurrentChange = (page) => {
  queryParams.page = page;
  fetchActivityList();
};

// 显示创建对话框
const showCreateDialog = () => {
  // 重置表单
  form.id = null;
  form.title = '';
  form.location = '';
  form.activityTime = [];
  form.registerTime = [];
  form.recruitNumber = 10;
  form.coverImg = '';
  form.description = '';
  form.team = '';
  form.status = 0;
  form.creatorId = userStore.userInfo.id;
  
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row) => {
  // 填充表单
  form.id = row.id;
  form.title = row.title;
  form.location = row.location;
  form.activityTime = [row.startTime, row.endTime];
  form.registerTime = [row.registerStartTime, row.registerEndTime];
  form.recruitNumber = row.recruitNumber;
  form.coverImg = row.coverImg;
  form.description = row.description;
  form.team = row.team;
  form.status = row.status;
  form.creatorId = row.creatorId;
  
  dialogVisible.value = true;
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除活动 "${row.title}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteActivity(row.id);
      if (res.code === 200) {
        ElMessage.success('删除成功');
        fetchActivityList();
      } else {
        ElMessage.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除活动失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 处理推荐状态变更
const handleRecommendChange = async (row) => {
  try {
    const res = await recommendActivity(row.id, row.isRecommended);
    if (res.code === 200) {
      ElMessage.success(row.isRecommended ? '已推荐到首页' : '已取消推荐');
    } else {
      // 恢复状态
      row.isRecommended = !row.isRecommended;
      ElMessage.error(res.message || '操作失败');
    }
  } catch (error) {
    // 恢复状态
    row.isRecommended = !row.isRecommended;
    console.error('更新推荐状态失败:', error);
    ElMessage.error('操作失败');
  }
};

// 更新活动状态
const updateStatus = async (id, status) => {
  try {
    const res = await updateActivityStatus(id, status);
    if (res.code === 200) {
      ElMessage.success('状态更新成功');
      fetchActivityList();
    } else {
      ElMessage.error(res.message || '状态更新失败');
    }
  } catch (error) {
    console.error('更新活动状态失败:', error);
    ElMessage.error('状态更新失败');
  }
};

// 处理封面上传
const handleCoverChange = (file) => {
  // 这里可以添加图片上传逻辑，暂时仅在本地预览
  form.coverImg = URL.createObjectURL(file.raw);
};

// 处理封面移除
const handleCoverRemove = () => {
  form.coverImg = '';
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      // 准备提交数据
      const data = {
        id: form.id,
        title: form.title,
        location: form.location,
        startTime: form.activityTime[0],
        endTime: form.activityTime[1],
        registerStartTime: form.registerTime[0],
        registerEndTime: form.registerTime[1],
        recruitNumber: form.recruitNumber,
        coverImg: form.coverImg,
        description: form.description,
        team: form.team,
        status: form.status,
        creatorId: form.creatorId
      };
      
      let res;
      if (form.id) {
        // 更新活动
        res = await updateActivity(form.id, data);
      } else {
        // 创建活动
        res = await createActivity(data);
      }
      
      if (res.code === 200) {
        ElMessage.success(form.id ? '更新成功' : '创建成功');
        dialogVisible.value = false;
        fetchActivityList();
      } else {
        ElMessage.error(res.message || (form.id ? '更新失败' : '创建失败'));
      }
    } catch (error) {
      console.error(form.id ? '更新活动失败:' : '创建活动失败:', error);
      ElMessage.error(form.id ? '更新失败' : '创建失败');
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  fetchActivityList();
});
</script>

<style scoped>
.activity-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9fafc;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 